# 重写Django的authenticate 支持手机号验证查询
import re

from django.contrib.auth.backends import ModelBackend
from apps.user1.models import User


class AuthModel(ModelBackend):
    # 重写用户验证方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 先判断是前台的请求还是后台的请求
        if request is None:
            # request说明是后台登录
            # 判断用户身份 是管理员还是普通用户
            try:
                user = User.objects.get(username=username, is_staff=True)
            except:
                # 捕获到异常说明，查询条件不符合，该用户不是管理，则直接返回空
                return None
            # 没有异常则验证密码
            if not user.check_password(password):
                # 校验失败返回空
                return None
            return user
        else:
            try:
                # 1、判断username是否是手机号
                if re.match(r'1[3-9]\d{9}', username):
                    # 按照手机号字段查询
                    user = User.objects.get(mobile=username)
                else:
                    # 按照用户名字段查询
                    user = User.objects.get(username=username)
            except:
                user = None

            if user is not None and user.check_password(password):
                # 校验密码
                return user
            return None